curl_multi_exec
运行当前 cURL 句柄的子连接
适用PHP版本:PHP 4及以上版本
curl_multi_exec 是PHP cURL扩展中的一个函数,用于并行执行多个cURL会话。它可以同时处理多个HTTP请求,在执行时不阻塞当前进程,使得多个请求能够在同一时间内完成,适用于高并发场景。
<span class="fun">int curl_multi_exec(resource $mh, int &$still_running)</span>
返回值为整数,表示执行的状态。返回值通常有以下几种情况:
以下是使用 curl_multi_exec 处理并行请求的示例代码:
$mh = curl_multi_init(); // 初始化多重cURL会话
// 初始化两个cURL会话
$ch1 = curl_init("http://example.com");
$ch2 = curl_init("http://example.org");
// 将cURL会话加入到多重句柄中
curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2);
$still_running = null; // 用于存储仍在运行的会话数
// 执行并行请求
do {
curl_multi_exec($mh, $still_running); // 执行请求
curl_multi_select($mh); // 等待活动会话
} while ($still_running > 0); // 如果还有会话在运行,则继续
// 获取结果
$response1 = curl_multi_getcontent($ch1);
$response2 = curl_multi_getcontent($ch2);
// 关闭cURL会话
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
// 输出请求结果
echo "Response from example.com: " . $response1 . "\n";
echo "Response from example.org: " . $response2 . "\n";
这段代码首先通过 curl_multi_init 创建一个多重cURL会话资源,然后分别初始化了两个cURL会话(请求两个不同的网站)。接着,使用 curl_multi_add_handle 将这些会话添加到多重句柄中。通过循环执行 curl_multi_exec,直到所有的会话都完成。每次循环后,使用 curl_multi_select 来等待活动的cURL会话。最后,获取请求结果,并关闭相关资源。